package com.code.generator.sqlgenerator.initexcel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.code.entity.generator.Column;
import com.code.entity.generator.Table;
import com.code.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelGenerator {

    public static void generateExcel() {
        List<Table> tables = ExcelMetadataProvider.getTableColumns();
        exportSheets(tables, "ai_gateway建表.xls");
        log.info("EXCEL文件生成成功================================");
    }

    private static void exportSheets(List<Table> tables, String fileName) {
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        for (Table table : tables) {
            // 创建参数对象
            ExportParams exportParams = new ExportParams();
            // 设置sheet得名称
            exportParams.setSheetName(table.getTableName());
            // 创建sheet使用得map
            Map<String, Object> dataMap = new HashMap<>(4);
            // title的参数为ExportParams类型
            dataMap.put("title", exportParams);
            // 模版导出对应得实体类型
            dataMap.put("entity", Column.class);
            //构造对象等同于@Excel
            // sheet中要填充得数据
            dataMap.put("data", table.getColumns());

            sheetsList.add(dataMap);
        }

        // 执行方法
        ExcelType excelType = ExcelType.HSSF;
        if (fileName.endsWith(".xlsx")) {
            excelType = ExcelType.XSSF;
        }
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, excelType);
        ExcelUtil.downLoadExcel(fileName, workbook);
    }

}
